package com.company.restaurant.service;

import com.company.restaurant.service.codec.ByteCodec;
import com.company.restaurant.service.codec.JsonDecoder;
import com.company.restaurant.service.codec.JsonEncoder;
import com.company.restaurant.service.handler.MessageHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.beans.ConstructorProperties;

/**
 * Created by User on 14.02.14.
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Service
public class NetworkManager implements ServerLifecycle {
    private static final Logger logger = LoggerFactory.getLogger(NetworkManager.class);

    private final ServerBootstrap bootstrap;
    private final String host;
    private final int port;
    private final int bossThreadCount;
    private final int workerThreadCount;

    @ConstructorProperties({"tcp.ip", "tcp.port", "netty.boss.thread", "netty.worker.thread"})
    public NetworkManager(String host, int port, int bossThreadCount, int workerThreadCount) {
        this.host = host;
        this.port = port;
        this.bossThreadCount = bossThreadCount;
        this.workerThreadCount = workerThreadCount;
        this.bootstrap = new ServerBootstrap();
    }

    @PostConstruct
    public void postConstruct() {
        logger.debug("!!!!!!!!!!!! NetworkManager PostConstruct ");
    }

    @Override
    public void init() throws Exception {
        logger.debug("!!!!!!!!!!!! NetworkManager init");

        bootstrap.group(new NioEventLoopGroup(bossThreadCount), new NioEventLoopGroup(workerThreadCount))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ByteCodec()).addLast(new MessageHandler());
                    }
                }).option(ChannelOption.SO_KEEPALIVE,true).option(ChannelOption.TCP_NODELAY, true);
        bootstrap.bind(host, port).sync();
    }

    @Override
    public void stop() throws Exception {
        logger.debug("!!!!!!!!!!!! NetworkManager stop");
    }
}
